
const https = require('https');

// 下载第三方模块  cnpm i cheerio -S
const cheerio = require("cheerio");

// https://search.jd.com/Search?keyword=%E8%8B%B9%E6%9E%9C&enc=utf-8&wq=%E8%8B%B9%E6%9E%9C&pvid=b855f6eb1c2c4fdf839715ef7812d343

// https.get(option,callback)
// option   string   => 请求的地址
//          object   => 请求的相关配置

// callback  请求成功时执行的回调函数
var str = "https://search.jd.com/Search?keyword=%E8%8B%B9%E6%9E%9C&enc=utf-8&wq=%E8%8B%B9%E6%9E%9C&pvid=b855f6eb1c2c4fdf839715ef7812d343"
https.get(str, function (res) {
    // console.log(res);

    var html = "";

    // 绑定data事件  => 当数据传递过来会触发回调函数
    res.on("data", function (chunk) {
        // console.log(chunk.toString());
        html += chunk;
    })

    // 绑定end事件  => 数据传输完毕之后 触发此回调函数
    res.on("end", function () {
        // console.log(html);
        var $ = cheerio.load(html);
        // console.log($);

        // console.log($("#J_goodsList .gl-warp>li").length);


        var list = $("#J_goodsList .gl-warp>li").map(function () {
            var data = {
                goodsId: $(this).attr("data-sku"),
                goodsName: $(this).find(".p-name").find("em").text(),
                goodsPrice: $(this).find(".p-price").find("i").text(),
                goodsImg: "https" + $(this).find(".p-img").find("img").get(0).attribs["data-lazy-img"],
            }
            // [img]
            // console.log($(this).find(".p-img").find("img").get(0).attribs["data-lazy-img"]);

            console.log(data);
            return data;
        }).get();

        console.log(list);

        const fsp = require('fs/promises');
        const { writeFile } = fsp;
        writeFile("./data/list.json", JSON.stringify(list), { encoding: "utf-8", flag: "w" }).then(() => {
            console.log("写入成功");
        }).catch(err => {
            console.log(err);
        })

    })

})